package com.jy.novel.service.system;

import com.jy.novel.common.CommonResult;
import com.jy.novel.common.Page;
import com.jy.novel.dao.system.MenuDao;
import com.jy.novel.pojo.form.MenuAddForm;
import com.jy.novel.pojo.form.MenuEditForm;
import com.jy.novel.pojo.system.MenuInfo;
import org.apache.commons.lang.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by jihb on 4/17/16.
 */
@Service
public class MenuService {

    @Autowired
    MenuDao menuDao;
    /**
     * 查询菜单列表
     * @param parentId
     * @return
     */
    public CommonResult<List<MenuInfo>> findMenuList(long parentId, Integer level){
        return CommonResult.returnDataWrap(menuDao.findMenuList(parentId,level));
    }

    /**
     * 查询菜单 分页
     * @param parentId
     * @param curPage
     * @param pageSize
     * @return
     */
    public CommonResult<Page<MenuInfo>> findMenuPage(long parentId, Integer level, int curPage, int pageSize){
        return CommonResult.returnDataWrap(menuDao.findMenuPage(parentId,level,curPage,pageSize));
    }

    /**
     * 查询菜单详情
     * @param id
     * @return
     */
    public CommonResult<MenuInfo> findMenuInfo(long id){
        return CommonResult.returnDataWrap(menuDao.findMenuInfo(id));
    }

    /**
     * 添加菜单
     * @param addForm
     * @return
     */
    public CommonResult<Boolean> addMenuInfo(MenuAddForm addForm){
        if (addForm == null){
            return CommonResult.returnFailure("缺少参数",false);
        }
        if (addForm.getParentId() == null){
            return CommonResult.returnFailure("缺少父菜单id",false);
        }
        if (addForm.getName() == null){
            return CommonResult.returnFailure("缺少菜单名称",false);
        }
        if(addForm.getLevel() == null){
            return CommonResult.returnFailure("缺少目录层级",false);
        }
        if(addForm.getLevel() != 2){
            addForm.setLeaf(false);
        }else{
            addForm.setLeaf(true);
        }
        addForm.setMenuId(new ObjectId().toHexString());
        if (addForm.getLeaf() != null && addForm.getLeaf() && StringUtils.isBlank(addForm.getPath())){
            return CommonResult.returnFailure("缺少菜单访问路径",false);
        }
        return CommonResult.returnBoolWrap(menuDao.addMenuInfo(addForm),"新增菜单失败");
    }

    /**
     * 更新菜单信息
     * @param editForm
     * @return
     */
    public CommonResult<Boolean> updateMenuInfo(MenuEditForm editForm, long id){
        if (editForm == null){
            return CommonResult.returnFailure("缺少参数",false);
        }
        return CommonResult.returnBoolWrap(menuDao.updateMenuInfo(editForm,id),"修改菜单失败");
    }

    /**
     * 删除菜单
     * @param id
     * @return
     */
    public CommonResult<Boolean> deleteMenuInfo(long id){
        return CommonResult.returnBoolWrap(menuDao.deleteMenuInfo(id),"删除菜单失败");
    }
}
